package org.jeecg.modules.charge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.checkerframework.checker.units.qual.C;
import org.jeecg.common.exception.ZoeException;
import org.jeecg.modules.charge.entity.BillPreCharge;
import org.jeecg.modules.charge.entity.ComCardInfo;
import org.jeecg.modules.charge.mapper.BillPreChargeMapper;
import org.jeecg.modules.charge.mapper.ComCardInfoMapper;
import org.jeecg.modules.charge.service.IBillPreChargeService;
import org.jeecg.modules.charge.service.IComCardInfoService;
import org.jeecg.modules.patient.entity.PatBasicInfo;
import org.jeecg.modules.patient.mapper.PatBasicInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @Description: 预交金票据
 * @Author: jeecg-boot
 * @Date: 2022-05-19
 * @Version: V1.0
 */
@Service
public class BillPreChargeServiceImpl extends ServiceImpl<BillPreChargeMapper, BillPreCharge> implements IBillPreChargeService {

    private final static String COLLECTION = "1";
    private final static String REFUND = "2";

    @Autowired
    private ComCardInfoMapper comCardInfoMapper;
    @Autowired
    private PatBasicInfoMapper patBasicInfoMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(BillPreCharge bill) {
        ComCardInfo cardInfo = comCardInfoMapper
                .selectOne(new QueryWrapper<ComCardInfo>().eq("patient_id", bill.getPatientId()));
        BigDecimal balance = new BigDecimal(0);
        String message = null;
        if (REFUND.equals(bill.getBillType())) {
            if (cardInfo.getBalance().compareTo(bill.getAmount()) < 0) {
                throw new ZoeException("退款金额大于余额");
            } else {
                //更新余额
                balance = cardInfo.getBalance().subtract(bill.getAmount());
            }
            message="退款成功";
        } else if (COLLECTION.equals(bill.getBillType())) {
            balance = cardInfo.getBalance().add(bill.getAmount());
            message="收款成功";
        }
        comCardInfoMapper.updateBalance(cardInfo.getPatientId(), balance);
        save(bill);
        return message;
    }

    @Override
    public Map<String, Object> accountInfo(String patientId) {
        ComCardInfo cardInfo = comCardInfoMapper
                .selectOne(new QueryWrapper<ComCardInfo>().eq("patient_id", patientId));
        PatBasicInfo basicInfo = patBasicInfoMapper.selectById(patientId);
        return null;
    }

}
